package com.sinoglobal.dumping.fragment.helper;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lidroid.xutils.BitmapUtils;
import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.activity.Dumpling_MainActivity;
import com.sinoglobal.dumping.api.Dumpling_RemoteImpl;
import com.sinoglobal.dumping.base.Dumpling_NetWorkUtil;
import com.sinoglobal.dumping.base.Dumpling_SinoAsyncTask;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_DumplingNumberBean;
import com.sinoglobal.dumping.bean.Dumpling_LogOutAcquireDumpling;
import com.sinoglobal.dumping.dumplinganim.DumplingAnimManager;
import com.sinoglobal.dumping.dumplingdialog.DumplingDialogHelper;
import com.sinoglobal.dumping.dumplingspring.AbsDumplingLayout;
import com.sinoglobal.dumping.dumplingspring.DumplingLayoutFactory;
import com.sinoglobal.dumping.dumplingtype.AbsDumplingType;
import com.sinoglobal.dumping.dumplingtype.DumplingTypeContext;
import com.sinoglobal.dumping.dumplingtype.DumplingTypeFactory;
import com.sinoglobal.dumping.fragment.Dumpling_HomeFragment;
import com.sinoglobal.dumping.util.DumplingCache;
import com.sinoglobal.dumping.util.Dumpling_HttpMethodSet;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Calendar;
import java.util.Random;

import static com.sinoglobal.dumping.base.Dumpling_SinoConstans.DUMPLING_TYPE;
import static com.sinoglobal.dumping.base.Dumpling_SinoConstans.GUO_GOLO_URL;
import static com.sinoglobal.dumping.util.DumplingUtils.getCoupon;
import static com.sinoglobal.dumping.util.DumplingUtils.getLogin;
import static com.sinoglobal.dumping.util.DumplingUtils.getMoney;

/**
 * Created by KeZhuang on 2016/1/14.
 */
public class Dumpling_HomefragmentImpl implements Dumpling_IHomeFragmentHelper{
    private Dumpling_HomeFragment fragment;

    private DumplingTypeFactory mTypeFactory = new DumplingTypeFactory();
    private DumplingTypeContext mTypeContext = new DumplingTypeContext();
    private DumplingLayoutFactory mLayoutFactory = new DumplingLayoutFactory();
    private DumplingAnimManager mAnimationManager;
    private DumplingCache mDumplingCache;

    public static Context mContext;
    private PendingIntent pendingIntent;
    private View noNet,hasNet;
    private TextView text2;
    private FrameLayout animatorLayout;
    public long maxDumplingCount = 0;
    private BitmapUtils bitmapUtils;
    public Dumpling_HomefragmentImpl(Dumpling_HomeFragment fragment){
        this.fragment = fragment;

    }
    static Dumpling_HomeFragment getFragment(){
        if(mContext!=null)
            return (Dumpling_HomeFragment) ((Dumpling_MainActivity)mContext).getFragmentByTag("0");
        return null;
    }

    @Override
    public void onViewCreate(View view) {
        view.scrollTo(0, 0);
        noNet = view.findViewById(R.id.no_network);
        hasNet = view.findViewById(R.id.have_network);
        text2 = (TextView) view.findViewById(R.id.text_2);
        fragment.text3 = (TextView) view.findViewById(R.id.tip_login);
        fragment.topBanner = (ImageView) view.findViewById(R.id.top_banner);
        fragment.text3.setVisibility(View.GONE);
        fragment.text3.setOnClickListener(fragment);
        view.findViewById(R.id.text_1).setVisibility(View.GONE);
        text2.setVisibility(View.GONE);
        view.findViewById(R.id.shaozi).setOnClickListener(fragment);
        fragment.ivDumpling = (ImageView) view.findViewById(R.id.jiaozi);
        animatorLayout = (FrameLayout) view.findViewById(R.id.lao_layout);
        fragment.llTimeLine = (LinearLayout) view.findViewById(R.id.timeline);
        fragment.tvLineLefttop = (TextView) view.findViewById(R.id.timeline_left_top);
        fragment.tvLineLeftbottom = (TextView) view.findViewById(R.id.timeline_left_bottom);
        fragment.tvLineCentertop = (TextView) view.findViewById(R.id.timeline_center_top);
        fragment.tvLineCenterbottom = (TextView) view.findViewById(R.id.timeline_center_bottom);
        fragment.tvLineRighttop = (TextView) view.findViewById(R.id.timeline_right_top);
        fragment.tvLineRightbottom = (TextView) view.findViewById(R.id.timeline_right_bottom);
    }
    @Override
    public void onActivityCreate() {
        fragment.parentActivity = (Dumpling_MainActivity) fragment.getActivity();
        fragment.showView(fragment.parentActivity.findViewById(R.id.dumpling_title_right_btn_treaty));
        fragment.parentActivity.mTemplateTitleText.setText("捞饺子");
        fragment.parentActivity.registerLogInListener(Dumpling_HomeFragment.class.getName(), fragment);

        mDumplingCache =new DumplingCache(fragment.getContext());
        mAnimationManager = new DumplingAnimManager(fragment);

        bitmapUtils = new BitmapUtils(fragment.parentActivity);
    }
    @Override
    public void onButtonClick(View v) {
        int id = v.getId();
        boolean isLogin = !Dumpling_SinoBaseActivity.isNoLogIn(fragment.parentActivity);
        if (id == R.id.shaozi) {
            if (isLogin && !mAnimationManager.isRunning()) {
                mAnimationManager.acquireloginUserDumpling();
                return;
            }
            createDumplingAnim();
            fragment.ivDumpling.setVisibility(View.GONE);
        } else if (id == R.id.tip_login) {
            if (mAnimationManager.isRunning()) {
                fragment.parentActivity.showToast("正在捞取中..");
                return;
            }
            DumplingDialogHelper.getDumpling_(fragment.parentActivity);
        }
    }
    @Override
    public boolean checkNetWork() {
        if (Dumpling_NetWorkUtil.getNetWork(fragment.getContext())) {
            noNet.setVisibility(View.VISIBLE);
            hasNet.setVisibility(View.GONE);
            noNet.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!checkNetWork()) {
                        fragment.clearTask();
                        queryDumplingMaxCount();
                        fragment.queryLoginOutCount(false, true);
                        fragment.addAcquireDumplingNum();
                        fragment.executeTask();
                    }
                }
            });
            return true;
        } else {
            hasNet.setVisibility(View.VISIBLE);
            noNet.setVisibility(View.GONE);
            return false;
        }
    }

    public DumplingAnimManager getAnimationManager() {
        return mAnimationManager;
    }

    @Override
    public void formatNumber(String count) {
        text2.setVisibility(View.VISIBLE);
        NumberFormat nf = new DecimalFormat("还剩#,###个饺子");
        int maxDumplingCount = Integer.parseInt(count);
        String surplusDumpling = nf.format(maxDumplingCount);
        text2.setText(surplusDumpling);
    }

    public long getMaxDumplingCount() {
        return maxDumplingCount;
    }

    @Override
    public void equalsDumplingType() {
        Dumpling_LogOutAcquireDumpling dumpling = fragment.getAcquireDumplingBean().getResultList().getDumpling();
        int type = Integer.parseInt(dumpling.getDumplingType());
        mDumplingCache.put(DUMPLING_TYPE,type);
        AbsDumplingType dumplingType = mTypeFactory.getType(fragment,type);
        mTypeContext.setType(dumplingType);
    }
    @Override
    public void createDumplingAnim() {
        mAnimationManager.getAnimation();
    }

    @Override
    public void setUpTip() {
        double dumplingMoney = getMoney(fragment.parentActivity);
        int couponCount = getCoupon(fragment.parentActivity);
        int state = getLogin(fragment.parentActivity);
        //未登录情况
        if (state == Dumpling_SinoConstans.LOGIN_STATE_LOGOUT) {
            //有钱就显示
            if (dumplingMoney != 0.0 || couponCount!=0) {
                managerTip(View.VISIBLE);
            } else {
                managerTip(View.GONE);
            }
        }
        //登录的情况
        if (state == Dumpling_SinoConstans.LOGIN_STATE_LOGIN) {
            //领取成功隐藏,失败就显示
            if (Dumpling_HttpMethodSet.isGetSucceed) {
                managerTip(View.GONE);
            } else {
                managerTip(View.VISIBLE);
            }
        }

        //退出登录的情况下
        if (state == Dumpling_SinoConstans.LOGIN_STATE_QUIT) {
            managerTip(View.GONE);
        }
    }
    @Override
    public void managerTip(int visiable) {
        double dumplingMoney = getMoney(fragment.parentActivity);
        int couponCount = getCoupon(fragment.parentActivity);
        if (visiable == View.GONE) {
            fragment.text3.setVisibility(View.GONE);
        } else {
                String str = "点击领取!";
                int start = 0;
                int length = str.length();
                SpannableString spanString = new SpannableString(str);
                AbsoluteSizeSpan aSpan = new AbsoluteSizeSpan(fragment.parentActivity.getResources().getDimensionPixelSize(R.dimen.h11));
                ForegroundColorSpan bCs = new ForegroundColorSpan(fragment.parentActivity.getResources().getColor(R.color.dumpling_orange_light));
                spanString.setSpan(aSpan, start, length, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                spanString.setSpan(bCs, start, length, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                String text = "";
                if(dumplingMoney!=0.0&&couponCount!=0){
                    text = "今日共捞到" + dumplingMoney + "元," + couponCount + "张优惠券";
                }
                if(dumplingMoney==0.0&&couponCount!=0){
                    text = "今日共捞到" + couponCount + "张优惠券";
                }
                if(dumplingMoney!=0.0&&couponCount==0){
                    text = "今日共捞到" + dumplingMoney + "元";
                }
                if(dumplingMoney==0.0&&couponCount==0){
                    text = "";
                    managerTip(View.GONE);
                }
                fragment.text3.setText(text+"\n");
                fragment.text3.append(spanString);
                fragment.text3.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void managerRandom() {
        Calendar calendar = Calendar.getInstance();
        AlarmManager am = (AlarmManager) fragment.parentActivity.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(fragment.parentActivity,Dumpling_AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(fragment.parentActivity,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        am.set(AlarmManager.RTC,calendar.getTimeInMillis(),pendingIntent);
        am.setRepeating(AlarmManager.RTC,calendar.getTimeInMillis(),1000,pendingIntent);
    }
    @Override
    public void updateMaxCount(int count){
        if (maxDumplingCount > 0) {
                if (maxDumplingCount > count) {
                    long maxCount = maxDumplingCount - count;
                    formatNumber(String.valueOf(maxCount));
                    maxDumplingCount = maxCount;
                }
            }
    }

    @Override
    public void cancelRandom() {
        AlarmManager am = (AlarmManager) fragment.parentActivity.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);
    }
    public static class Dumpling_AlarmReceiver extends BroadcastReceiver{
        private Random random;
        @Override
        public void onReceive(Context context, Intent intent) {
            if(mContext!=null){
                if(random==null){
                    random= new Random();
                }
                int randomInt = random.nextInt(10);
                while (randomInt == 0) {
                    randomInt = random.nextInt(10);
                }
                if(getFragment()!=null){
                    getFragment().helper.updateMaxCount(randomInt);
                }
            }
        }
    }
    /**
     * 查询最大饺子数量接口
     */
    @Override
    public void queryDumplingMaxCount() {
        new Dumpling_SinoAsyncTask<Object, Void, Dumpling_DumplingNumberBean>(fragment.parentActivity, true, true) {
            @Override
            public Dumpling_DumplingNumberBean before(Object... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().queryDumplingNum();
            }

            @Override

            public void after(Dumpling_DumplingNumberBean dumplingNum) {
                if (dumplingNum != null) {
                    if (dumplingNum.getCode() == Dumpling_SinoConstans.SUCCESS_CODE) {
                        String count = dumplingNum.getResultList().getNum();
                        maxDumplingCount = Integer.parseInt(count);
                        if (maxDumplingCount != 0) {
                            formatNumber(count);
                        }
                        String voteUrl = dumplingNum.getResultList().getVoteUrl();
                        String laoLogo = dumplingNum.getResultList().getLaoLogo();
                        bitmapUtils.display((ImageView)fragment.getView(R.id.guo_logo),laoLogo);
                        boolean isChangeUI= dumplingNum.getResultList().getTimeup().equals("1");
                        boolean isVote = dumplingNum.getResultList().getVote().equals("1");
                        fragment.getParentActivity().setVoteUrl(voteUrl);
                        AbsDumplingLayout layout = mLayoutFactory.getLayout(fragment,isChangeUI);
                        if(fragment.getObservable().size()==0){
                            fragment.getObservable().addElement(fragment.parentActivity);
                            fragment.getObservable().addElement(layout);
                        }
                        fragment.getObservable().notifyChange(fragment,isChangeUI,isVote);
                    } else {
                        dismissWaitingDialog();
                    }
                }
            }

            @Override
            public void exception() {

            }
        }.execute();
    }
    @Override
    public void cancelAnimation(){
        animatorLayout.clearAnimation();

    }
}
